package top.yuyufeng.ticketassistant;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import top.yuyufeng.ticketassistant.utils.MyDateUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author yuyufeng
 * @date 2018/1/16
 */
public class App {
    private static Random random = new Random();
    private static String urlSrc = "https://kyfw.12306.cn/passport/captcha/captcha-image?login_site=E&module=login&rand=sjrand&" + random.nextDouble();


    public static void main(String[] args) throws IOException {

//        Map<String, String> cookies = getValidImageAndCookies();

//        doValidCheck(cookies);
        Map<String, String> cookies = new HashMap<>();
        cookies.put("_passport_session","0e37c61c7eb44022a812be402ad178329612");
        cookies.put("_passport_ct","6008c2a7374949dba5f6ca1e0b10b802t7975");
        cookies.put("BIGipServerpool_passport","334299658.50215.0000");

        Map<String, String> headers = new HashMap<>(20);
        String host = "https://kyfw.12306.cn";
        String path = "/otn/index/initMy12306";
        headers = new HashMap<>();
        headers.put("Accept", "*/*");
        headers.put("Accept-Encoding", "gzip, deflate, br");
        headers.put("Accept-Language", "zh-CN,zh;q=0.9");
        headers.put("Cache-Control", "no-cache");
        headers.put("Connection", "keep-alive");
        headers.put("Host", "kyfw.12306.cn");
        headers.put("If-Modified-Since", "0");
        headers.put("X-Requested-With", "XMLHttpRequest");
        headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
        headers.put("Referer", "https://kyfw.12306.cn/otn/index/init");
        System.out.println("开始抓取：" + host + path);
        Map<String, String> datas = new HashMap<>();
        datas.put("username", "yyfyyf1994");
        datas.put("password", "yyfyyf1994");
        datas.put("appid", "otn");
        Connection conn = Jsoup.connect(host + path)
                .followRedirects(true)
                .data(datas)
                .cookies(cookies)
                .method(Connection.Method.POST)
                .timeout(5000)
                .ignoreContentType(true)
                .headers(headers);

        Connection.Response response = conn.execute();

        cookies = response.cookies();
        for (String cookie : cookies.keySet()) {
            System.out.println(cookie + ' ' + cookies.get(cookie));
        }
        Document doc = response.parse();
        String textResult = doc.body().text();
        System.out.println(textResult);

    }

    private static void doValidCheck(Map<String, String> cookies) throws IOException {
        Map<String, String> headers = new HashMap<>(20);
        String host = "https://kyfw.12306.cn";
        String path = "/passport/captcha/captcha-check";
        headers = new HashMap<>();
        headers.put("Accept", "*/*");
        headers.put("Accept-Encoding", "gzip, deflate, br");
        headers.put("Accept-Language", "zh-CN,zh;q=0.9");
        headers.put("Cache-Control", "no-cache");
        headers.put("Connection", "keep-alive");
        headers.put("Host", "kyfw.12306.cn");
        headers.put("If-Modified-Since", "0");
        headers.put("X-Requested-With", "XMLHttpRequest");
        headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
        headers.put("Referer", "https://kyfw.12306.cn/otn/index/init");
        System.out.println("开始抓取：" + host + path);
        Map<String, String> datas = new HashMap<>();
        datas.put("login_site", "E");
        String location = "119,29,198,107";
        datas.put("answer", location);
        datas.put("rand", "sjrand");
        Connection conn = Jsoup.connect(host + path)
                .followRedirects(true)
                .data(datas)
                .cookies(cookies)
                .method(Connection.Method.GET)
                .timeout(5000)
                .ignoreContentType(true)
                .headers(headers);

        Connection.Response response = conn.execute();

        cookies = response.cookies();
        for (String cookie : cookies.keySet()) {
            System.out.println(cookie + ' ' + cookies.get(cookie));
        }
        Document doc = response.parse();
        String textResult = doc.body().text();
        System.out.println(textResult);
    }


    private static Map<String, String> getValidImageAndCookies() throws IOException {
        String imgDoc = "d://test/";
        String imgName = "test.jpeg";

        Map<String, String> cookies = new HashMap<>();
        Map<String, String> headers = new HashMap<>(20);
        String host = "https://kyfw.12306.cn";
        String path = "/passport/captcha/captcha-image";
        headers = new HashMap<>();
        headers.put("Accept", "*/*");
        headers.put("Accept-Encoding", "gzip, deflate, br");
        headers.put("Accept-Language", "zh-CN,zh;q=0.9");
        headers.put("Cache-Control", "no-cache");
        headers.put("Connection", "keep-alive");
        headers.put("Host", "kyfw.12306.cn");
        headers.put("If-Modified-Since", "0");
        headers.put("X-Requested-With", "XMLHttpRequest");
        headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
        headers.put("Referer", "https://kyfw.12306.cn/otn/index/init");
        System.out.println("开始抓取：" + host + path);
        Map<String, String> datas = new HashMap<>();
        datas.put("login_site", "E");
        datas.put("module", "login");
        datas.put("rand", "sjrand");
        datas.put("random", random.nextDouble() + "");
        Connection conn = Jsoup.connect(host + path)
                .followRedirects(true)
                .data(datas)
//                .cookies(cookies)
                .method(Connection.Method.GET)
                .timeout(5000)
                .ignoreContentType(true)
                .headers(headers);

        Connection.Response response = conn.execute();
        byte[] validImageBytes = response.bodyAsBytes();
        FileOutputStream fos = new FileOutputStream(imgDoc + imgName);
        fos.write(validImageBytes);
        fos.close();

        cookies = response.cookies();
        for (String cookie : cookies.keySet()) {
            System.out.println(cookie + ' ' + cookies.get(cookie));
        }
        return cookies;
    }


    private static Map<String, String> initIndex() throws IOException {
        Map<String, String> cookies;
        Map<String, String> headers = new HashMap<>(20);
        String host = "https://kyfw.12306.cn";
        String path = "/otn/leftTicket/init";
        headers = new HashMap<>();
        headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
        headers.put("Accept-Encoding", "gzip, deflate, br");
        headers.put("Accept-Language", "zh-CN,zh;q=0.9");
        headers.put("Cache-Control", "no-cache");
        headers.put("Connection", "keep-alive");
        headers.put("Host", "kyfw.12306.cn");
        headers.put("Upgrade-Insecure-Requests", "1");
        headers.put("X-Requested-With", "XMLHttpRequest");
        headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
        headers.put("Referer", "https://kyfw.12306.cn/otn/index/init");
        System.out.println("开始抓取：" + host + path);
        Connection conn = Jsoup.connect(host + path)
                .followRedirects(true)
                .method(Connection.Method.GET)
                .timeout(5000)
                .ignoreContentType(true)
                .headers(headers);

        Connection.Response response = conn.execute();
//        Document doc = response.parse();
//        String textResult = doc.body().text();
        cookies = response.cookies();

        for (String cookie : cookies.keySet()) {
            System.out.println(cookie + ' ' + cookies.get(cookie));
        }
        return cookies;
    }


    public static void sslClient(HttpClient httpClient) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @Override
                public void checkClientTrusted(X509Certificate[] xcs, String str) {

                }

                @Override
                public void checkServerTrusted(X509Certificate[] xcs, String str) {

                }
            };
            ctx.init(null, new TrustManager[]{tm}, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx);
            ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm = httpClient.getConnectionManager();
            SchemeRegistry registry = ccm.getSchemeRegistry();
            registry.register(new Scheme("https", 443, ssf));
        } catch (KeyManagementException ex) {
            throw new RuntimeException(ex);
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException(ex);
        }
    }
}
